import axios from "axios";
import DEV_ADDRESS from "./DEV_ADDRESS";
import { ElMessage } from "element-plus";

import { getToken, cleareAll, refreshToken, saveToken } from "@/util/auth";
import { useRouter } from "vue-router";

const router = useRouter();

const instance = axios.create({
  baseURL: DEV_ADDRESS,
  timeout: 3000,
});

//配置拦截器
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // 拦截请求 加上token？
    config.headers.token = getToken();
    console.log("config", config);
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {

    console.log(response,"responese data ");
   

    if (response.data.code != 200) {
        console.log("resp,", response.data.code);
        // token超时  后台重新发放token
      if (response.data.code == 203) {
        ElMessage({
          message: response.data.message + "203",
          type: "error",
        });
         refreshToken();

        return Promise.resolve(response.data);
      }

      

      // 请求失败就返回失败的数据 提示失败弹窗
      ElMessage({
        message: response.data.message,
        type: "error",
      });
      return Promise.reject("error");
    }

    // 成功来处理
    return Promise.resolve(response.data);
  },
  function (error) {
    ElMessage({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

// 导出对象
export default instance;
